package com.common.server.common.util;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.common.server.common.config.zxingcode.BufferedImageLuminanceSource;
import com.common.server.common.config.zxingcode.LogoConfig;
import com.common.server.modules.qrcode.entity.ZXingCode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：二维码工具类 google zxing
 * <p>
 * 作者：Ostrich Hu
 * 时间：2019/10/12 17:54 星期六
 */
public class ZXingCodeUtil {

    private static final String CHARSET = "UTF-8";

    /**
     * 二维码图片添加Logo
     *
     * @param bim        图片流
     * @param logoPic    Logo图片物理位置
     * @param logoConfig Logo图片设置参数
     * @throws Exception 异常上抛
     */
    private static void addLogo_QRCode(BufferedImage bim, File logoPic, LogoConfig logoConfig) throws Exception {
        // 对象流传输
        Graphics2D g = bim.createGraphics();

        // 读取Logo图片
        BufferedImage logo = ImageIO.read(logoPic);

        // 设置logo的大小,本人设置为二维码图片的20%,因为过大会盖掉二维码
        int widthLogo = Math.min(logo.getWidth(null), bim.getWidth() * 2 / 10);
        int heightLogo = logo.getHeight(null) > bim.getHeight() * 2 / 10 ? (bim.getHeight() * 2 / 10) : logo.getWidth(null);

        // 计算图片放置位置
        // logo放在中心
        int x = (bim.getWidth() - widthLogo) / 2;
        int y = (bim.getHeight() - heightLogo) / 2;
        // 开始绘制图片
        g.drawImage(logo, x, y, widthLogo, heightLogo, null);
        g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
        g.setStroke(new BasicStroke(logoConfig.getBorder()));
        g.setColor(logoConfig.getBorderColor());
        g.drawRect(x, y, widthLogo, heightLogo);
        g.dispose();
        logo.flush();
        bim.flush();
    }

    /**
     * 二维码的解析
     *
     * @param image 图片文件流
     * @return 解析后的Result结果集
     * @throws Exception 错误异常上抛
     */
    @SuppressWarnings("unchecked")
    public static Result parseQR_CODEImage(BufferedImage image) throws Exception {
        // 设置解析
        MultiFormatReader formatReader = new MultiFormatReader();

        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        return formatReader.decode(binaryBitmap, hints);
    }

    /**
     * 生成二维码bufferedImage图片
     *
     * @param zxingconfig 二维码配置信息
     * @return 生成后的 BufferedImage
     * @throws Exception 异常上抛
     */
    public static BufferedImage getQR_CODEBufferedImage(ZXingCode zxingconfig) throws Exception {
        // Google配置文件
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

        // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
        BitMatrix bm = multiFormatWriter.encode(zxingconfig.getContent(), zxingconfig.getBarcodeformat(), zxingconfig.getWidth(), zxingconfig.getHeight(),
                zxingconfig.getHints());

        int w = bm.getWidth();
        int h = bm.getHeight();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

        // 开始利用二维码数据创建Bitmap图片，分别设为黑白两色
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                image.setRGB(x, y, bm.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }

        // 是否设置Logo图片
        if (zxingconfig.isLogoFlg()) {
            addLogo_QRCode(image, new File(zxingconfig.getLogoPath()), zxingconfig.getLogoConfig());
        }
        return image;
    }

    /**
     * 设置二维码的格式参数
     *
     * @return
     */
    public static Map<EncodeHintType, Object> getDecodeHintType() {
        // 用于设置QR二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 0);
        return hints;
    }
}
